using DealerPlatform.Common.TokenModule;
using DealerPlatform.Common.TokenModule.Models;
using DealerPlatform.Service.CustomerApp;
using DealerPlatform.Service.CustomerApp.Dtos;
using Microsoft.AspNetCore.Mvc;

namespace DealerPlatform.Web.Controllers;

public class LoginController(
    ICustomerService customerService,
    IConfiguration configuration) : BaseController
{
    [HttpPost]
    public async Task<string> CheckPassword(CustomerLoginDto dto)
    {
        if (string.IsNullOrWhiteSpace(dto.CustomerNo)||string.IsNullOrWhiteSpace(dto.Password))
        {
            HttpContext.Response.StatusCode = 400;
            return "NonLoginInfo";
        }

        var isSuccess = await customerService.CheckPassword(dto);
        if (isSuccess)
        {
            // 获取用户真实数据
            var customer = await customerService.GetCustomerAsync(dto.CustomerNo);
            return GetToken(customer.Id, customer.CustomerNo, customer.CustomerName);
        }
        HttpContext.Response.StatusCode = 400;
        return "NonUser";
    }

    private string GetToken(int customerId, string customerNo, string customerName)
    {
        var token = configuration.GetSection("Jwt").Get<JwtTokenModel>();
        token.Id = customerId;
        token.CustomerNo = customerNo;
        token.CustomerName = customerName;
        return TokenHelper.CreateToken(token);
    }
}